#Script to extract IP's from email headers designated as spam
# Michael Gichoga 12/2010
use strict;
use warnings;
use Net::IMAP::Simple;
use Email::Simple;
use Socket;

#Variables
my $exceptionfile='exception.txt'; #IPs you that are exceptions - e.g your servers IP, localhost etc
my $email_server ='';
my $user=''; #username
my $pwd=''; #password
my $folder='Spams'; #This folder must exist in your e-mail account
####

my ($hash,$hash2)=\();


#iterate through exception file to make sure we don't block our servers
open( FILE2, "< $exceptionfile" ) or die "Can't open $exceptionfile : $!";
     
        while( <FILE2> ) {
		chomp($_);
        $hash2->{$_}=1;
        }
close FILE2;   
# open a connection to the IMAP server
my $server = new Net::IMAP::Simple( "$email_server" );

# login
$server->login( "$user", "$pwd" );

#Select folder
my $number_of_messages = $server->select($server->mailboxes("$folder"));

my %uniqueIPs = ();
#Loop through each message and extract header, add IP if not found in spamfile and exceptionfile
foreach my $msg ( 1 .. $number_of_messages ) {
        my $email = Email::Simple->new( join '', @{$server->get( $msg )} );
        my @headers = $email->header_pairs;
	
        if($headers[3]=~ /(\[.*\])/){
        	my $ip_address = $1;
      		$ip_address=~s/\[//g;
      		$ip_address=~s/\]//g;
      		if ( !exists $hash2->{$ip_address}){
				$uniqueIPs{$ip_address} = 1;
			#print "$ip_address";
			}
      		
        }
}

for my $ip (keys %uniqueIPs) #Print Unuqie IPs
{
	my $iaddr = inet_aton("$ip");
	print "$ip\n";
	
}
undef %uniqueIPs;
undef $hash;
undef $hash2; 
#Disconnect
$server->quit();
